import React, { useState } from 'react'
import WeatherCard from '../components/WeatherCard'
import WeatherForecast from '../components/WeatherForecast'
import LifeAdvice from '../components/LifeAdvice'
import Loader from '../components/Loader'
import CitySearch from '../components/CitySearch'
import { HEFENG_API_KEY } from '../config'

export default function WeatherPage() {
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState(null)
  const [forecastData, setForecastData] = useState([]) // 存储未来天气预报
  const [error, setError] = useState(null)
  const [currentCityCode, setCurrentCityCode] = useState('101010100') // 默认北京
  const [currentCityName, setCurrentCityName] = useState('北京')
  const [searchMethod, setSearchMethod] = useState('city') // 'city' 或 'code'
  const [cityCodeInput, setCityCodeInput] = useState('')
  const [selectedCityInfo, setSelectedCityInfo] = useState({ adcode: '', name: '' }) // 保存选择的城市信息

  // 模拟天气数据，作为API调用失败时的备选
  const getMockWeatherData = (cityCode, cityName) => {
    // 根据不同城市码返回不同的模拟数据
    const mockDataMap = {
      '101010100': { temp: '25', text: '晴', humidity: '45', windDir: '东南风', windScale: '3' },
      '101020100': { temp: '28', text: '多云', humidity: '65', windDir: '南风', windScale: '2' },
      '101280101': { temp: '32', text: '雷阵雨', humidity: '80', windDir: '西南风', windScale: '4' },
      '101280601': { temp: '30', text: '阴', humidity: '70', windDir: '东风', windScale: '3' }
    };
    
    const mockData = mockDataMap[cityCode] || { temp: '22', text: '晴', humidity: '50', windDir: '北风', windScale: '2' };
    
    // 生成未来5天的模拟预报数据
    const mockForecast = [];
    const currentTemp = parseInt(mockData.temp);
    const conditions = ['晴', '多云', '阴', '小雨', '晴转多云'];
    
    for (let i = 1; i <= 5; i++) {
      const date = new Date();
      date.setDate(date.getDate() + i);
      
      const randomTempOffset = Math.floor(Math.random() * 6) - 3; // -3到+2的随机温差
      const maxTemp = currentTemp + randomTempOffset;
      const minTemp = maxTemp - Math.floor(Math.random() * 5) - 3; // 最低温度比最高低3-7度
      
      mockForecast.push({
        date: date.toISOString().split('T')[0],
        condition: conditions[Math.floor(Math.random() * conditions.length)],
        maxTemp: maxTemp.toString(),
        minTemp: minTemp.toString()
      });
    }
    
    const weatherData = {
      city: cityName,
      temperature: mockData.temp,
      unit: '°C',
      condition: mockData.text,
      humidity: mockData.humidity,
      wind: `${mockData.windDir} ${mockData.windScale}级`,
      updatedAt: new Date().toLocaleString('zh-CN'),
      iconCode: '100',
      isMock: true // 标记这是模拟数据
    };
    
    return { weatherData, forecastData: mockForecast };
  };
  
  // 获取天气数据函数
  async function fetchWeather(cityCode = currentCityCode, cityName = currentCityName) {
    setError(null);
    setLoading(true);
    
    console.log(`正在获取${cityName}(${cityCode})的天气数据...`);
    
    // 首先使用模拟数据作为演示
    try {
      // 直接使用模拟数据，确保UI能正常显示
      const { weatherData, forecastData: mockForecast } = getMockWeatherData(cityCode, cityName);
      setData(weatherData);
      setForecastData(mockForecast);
      
      // 在后台尝试真实API调用，但不影响用户体验
      try {
        console.log('尝试调用真实天气API...');
        const url = `https://devapi.qweather.com/v7/weather/now?location=${cityCode}&key=${HEFENG_API_KEY}`;
        console.log(`API请求URL: ${url}`);
        
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 5000); // 5秒超时
        
        const res = await fetch(url, { signal: controller.signal });
        clearTimeout(timeoutId);
        
        console.log(`API响应状态: ${res.status}`);
        
        if (!res.ok) {
          throw new Error(`HTTP错误! 状态: ${res.status}`);
        }
        
        const json = await res.json();
        console.log('API响应数据:', json);
        
        if (json.code === '200' && json.now) {
          // 如果API调用成功，更新为真实数据
          setData({
            city: cityName,
            temperature: json.now.temp,
            unit: '°C',
            condition: json.now.text,
            humidity: json.now.humidity,
            wind: `${json.now.windDir} ${json.now.windScale}级`,
            updatedAt: new Date().toLocaleString('zh-CN'),
            iconCode: json.now.icon
          });
          
          // 尝试获取未来天气预报
          try {
            console.log('尝试获取未来天气预报...');
            const forecastUrl = `https://devapi.qweather.com/v7/weather/3d?location=${cityCode}&key=${HEFENG_API_KEY}`;
            const forecastRes = await fetch(forecastUrl, { signal: controller.signal });
            
            if (forecastRes.ok) {
              const forecastJson = await forecastRes.json();
              console.log('天气预报API响应数据:', forecastJson);
              
              if (forecastJson.code === '200' && forecastJson.daily) {
                const realForecast = forecastJson.daily.map(day => ({
                  date: day.fxDate,
                  condition: day.textDay,
                  maxTemp: day.tempMax,
                  minTemp: day.tempMin
                }));
                setForecastData(realForecast);
              }
            }
          } catch (forecastError) {
            console.log('获取真实天气预报失败，继续使用模拟数据:', forecastError.message);
          }
        } else {
          console.log(`API返回错误代码: ${json.code || '未知'}`);
        }
      } catch (apiError) {
        // API调用失败，但不影响用户体验
        console.log('真实API调用失败，继续使用模拟数据:', apiError.message);
      }
    } catch (err) {
      // 捕获所有可能的错误
      console.error('天气数据处理失败:', err);
      setError(`获取天气数据失败: ${err.message || '未知错误'}`);
      setForecastData([]);
    } finally {
      setLoading(false);
    }
  }

  // 处理城市选择
  function handleCitySelect(adcode, name) {
    setSelectedCityInfo({ adcode, name })
    setCurrentCityCode(adcode)
    setCurrentCityName(name)
    fetchWeather(adcode, name)
  }
  
  // 处理城市名称搜索查询
  function handleCitySearch() {
    if (selectedCityInfo.adcode && selectedCityInfo.name) {
      fetchWeather(selectedCityInfo.adcode, selectedCityInfo.name)
    } else {
      setError('请先选择一个城市')
    }
  }

  // 处理城市码搜索
  function handleCodeSearch() {
    if (cityCodeInput.trim() && !loading) {
      // 验证是否为纯数字城市码
      if (!cityCodeInput.trim().match(/^\d+$/)) {
        setError('请输入有效的城市码(数字)');
        return;
      }
      fetchWeather(cityCodeInput.trim(), `城市(${cityCodeInput.trim()})`)
    }
  }

  return (
    <div style={{ 
      padding: 24, 
      maxWidth: 800, 
      margin: '0 auto',
      fontFamily: 'Segoe UI, Roboto, Helvetica, Arial, sans-serif'
    }}>
      <h1 style={{ fontSize: 28, fontWeight: 600, color: '#0f172a', marginBottom: 24 }}>实时天气查询</h1>
      
      {/* 统一搜索区域 */}
      <div style={{ 
        marginBottom: 24, 
        padding: 20,
        backgroundColor: '#f8fafc',
        borderRadius: 12,
        border: '1px solid #e2e8f0'
      }}>
        {/* 搜索方式切换 */}
        <div style={{ 
          display: 'flex', 
          marginBottom: 15,
          backgroundColor: '#e2e8f0',
          borderRadius: 8,
          padding: 4,
          width: 'fit-content'
        }}>
          <button
            onClick={() => setSearchMethod('city')}
            style={{
              padding: '8px 16px',
              borderRadius: 6,
              border: 'none',
              backgroundColor: searchMethod === 'city' ? '#ffffff' : 'transparent',
              color: searchMethod === 'city' ? '#0f172a' : '#64748b',
              fontSize: 14,
              fontWeight: 500,
              cursor: 'pointer',
              transition: 'all 0.2s'
            }}
          >
            城市名称搜索
          </button>
          <button
            onClick={() => setSearchMethod('code')}
            style={{
              padding: '8px 16px',
              borderRadius: 6,
              border: 'none',
              backgroundColor: searchMethod === 'code' ? '#ffffff' : 'transparent',
              color: searchMethod === 'code' ? '#0f172a' : '#64748b',
              fontSize: 14,
              fontWeight: 500,
              cursor: 'pointer',
              transition: 'all 0.2s'
            }}
          >
            城市码查询
          </button>
        </div>
        
        {/* 根据选择的搜索方式显示对应的输入界面 */}
        {searchMethod === 'city' ? (
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
            <div style={{ flex: 1, minWidth: 200 }}>
              <CitySearch 
                onSelectAdcode={(adcode, name) => {
                  // 保存选择的城市信息但不立即查询
                  setSelectedCityInfo({ adcode, name: name || `城市(${adcode})` });
                }}
                placeholder="搜索城市名称获取天气"
              />
            </div>
            <button 
              onClick={handleCitySearch}
              style={{
                padding: '10px 20px',
                borderRadius: 8,
                border: 'none',
                backgroundColor: loading ? '#93c5fd' : '#0ea5e9',
                color: 'white',
                fontSize: 16,
                cursor: loading ? 'not-allowed' : 'pointer',
                fontWeight: 500,
                transition: 'background-color 0.2s'
              }}
              onMouseEnter={(e) => !loading && (e.target.style.backgroundColor = '#0284c7')}
              onMouseLeave={(e) => !loading && (e.target.style.backgroundColor = '#0ea5e9')}
              disabled={loading || !selectedCityInfo.adcode}
            >
              查询天气
            </button>
          </div>
        ) : (
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
            <input
              type="text"
              value={cityCodeInput}
              onChange={(e) => setCityCodeInput(e.target.value)}
              onKeyPress={(e) => {
                if (e.key === 'Enter') handleCodeSearch();
              }}
              placeholder="请输入城市码(纯数字)"
              style={{
                padding: '10px 12px',
                borderRadius: 8,
                border: '1px solid #d1d5db',
                fontSize: 16,
                minWidth: 200,
                flex: 1
              }}
              disabled={loading}
            />
            <button 
              onClick={handleCodeSearch}
              style={{
                padding: '10px 20px',
                borderRadius: 8,
                border: 'none',
                backgroundColor: loading ? '#93c5fd' : '#0ea5e9',
                color: 'white',
                fontSize: 16,
                cursor: loading ? 'not-allowed' : 'pointer',
                fontWeight: 500,
                transition: 'background-color 0.2s'
              }}
              onMouseEnter={(e) => !loading && (e.target.style.backgroundColor = '#0284c7')}
              onMouseLeave={(e) => !loading && (e.target.style.backgroundColor = '#0ea5e9')}
              disabled={loading || !cityCodeInput.trim()}
            >
              查询天气
            </button>
          </div>
        )}
        
        {/* 快捷按钮 */}
        <div style={{ marginTop: 15, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <button 
            onClick={() => fetchWeather('101010100', '北京')}
            style={{
              padding: '8px 16px',
              borderRadius: 8,
              border: '1px solid #d1d5db',
              backgroundColor: loading ? '#f1f5f9' : '#f8fafc',
              fontSize: 14,
              cursor: loading ? 'not-allowed' : 'pointer',
            transition: 'background-color 0.2s'
          }}
          onMouseEnter={(e) => !loading && (e.target.style.backgroundColor = '#f1f5f9')}
          onMouseLeave={(e) => !loading && (e.target.style.backgroundColor = '#f8fafc')}
          disabled={loading}
        >
          {loading ? '加载中...' : '北京天气'}
        </button>
        </div>
      </div>

      {/* 加载状态 */}
      {loading && (
        <div style={{ 
          textAlign: 'center', 
          padding: 40,
          minHeight: 300,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center'
        }}>
          <Loader size={64} text="正在获取天气信息..." />
        </div>
      )}

      {/* 错误信息 */}
      {error && (
        <div style={{ 
          color: '#dc2626', 
          backgroundColor: '#fef2f2', 
          border: '1px solid #fecaca',
          borderRadius: 8,
          padding: 16,
          marginBottom: 20
        }}>
          {error}
        </div>
      )}

      {/* 天气卡片展示 */}
      {data && !loading && <WeatherCard {...data} />}
      
      {/* 未来天气预报 */}
      {data && !loading && (
        <WeatherForecast 
          forecastData={forecastData} 
          isMock={data.isMock} 
        />
      )}
      
      {/* 生活建议 */}
      {data && !loading && (
        <LifeAdvice 
          weatherData={data} 
          isMock={data.isMock} 
        />
      )}
      
      {/* 最近查询信息 */}
      {data && !loading && (
        <div style={{ 
          marginTop: 16, 
          fontSize: 14, 
          color: '#64748b',
          textAlign: 'right'
        }}>
          上次更新: {data.updatedAt}
        </div>
      )}
      
      {/* 初始状态提示 */}
      {!data && !loading && !error && (
        <div style={{ 
          textAlign: 'center', 
          padding: 40,
          color: '#64748b',
          backgroundColor: '#f8fafc',
          borderRadius: 8,
          border: '1px dashed #cbd5e1'
        }}>
          <p>请使用上方搜索框查询天气，您可以选择城市名称搜索或城市码查询</p>
          <div style={{ marginTop: 20, textAlign: 'left', maxWidth: 400, margin: '20px auto' }}>
            <p>常用城市码：</p>
            <ul style={{ listStyle: 'none', paddingLeft: 0, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              <li style={{ margin: '5px 0', padding: '8px', backgroundColor: '#f1f5f9', borderRadius: 6, textAlign: 'center' }}>
                北京: 101010100
              </li>
              <li style={{ margin: '5px 0', padding: '8px', backgroundColor: '#f1f5f9', borderRadius: 6, textAlign: 'center' }}>
                上海: 101020100
              </li>
              <li style={{ margin: '5px 0', padding: '8px', backgroundColor: '#f1f5f9', borderRadius: 6, textAlign: 'center' }}>
                广州: 101280101
              </li>
              <li style={{ margin: '5px 0', padding: '8px', backgroundColor: '#f1f5f9', borderRadius: 6, textAlign: 'center' }}>
                深圳: 101280601
              </li>
            </ul>
          </div>
        </div>
      )}
    </div>
  )
}
